package com.itheima.mp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.apache.tomcat.jni.Address;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//继承


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {
@Autowired
UserMapper userMapper;

    @Override
    public void deductBalance(Long id, Integer money) {
        //查询用户
     User user=getById(id);
     if (user==null||user.getStatus()==2){
         throw new RuntimeException("用户状态异常!");
        }
     if(user.getBalance()<money){
         throw new RuntimeException("用户余额不足!");
     }
     //扣除金额，最后面的update表示执行
       int remainBalance=user.getBalance()-money;
       lambdaUpdate()
               .set(User::getBalance,remainBalance)
               .set(remainBalance==0,User::getStatus,2)
               .eq(User::getId,id)
               .eq(User::getBalance,user.getBalance())//乐观锁
               .update();
    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        //构建条件,结果返回符合条件的用户
        List<User> userList=lambdaQuery().like(name!=null,User::getUsername,name)
                .like(status!=null,User::getStatus,status)
                .eq(maxBalance!=null,User::getBalance,minBalance)
                .le(maxBalance!=null,User::getBalance,maxBalance)
                .list();
        return userList;
    }

    @Override
    public UserVO queryUserAndAddressById(Long id) {
        return null;
    }


}
